<?php

/**
 * Variable Controller
 */
class AdminController extends AppController
{
  var $name = "Admin";

	function index()
	{
		$this->render('admin', 'admin');
		#-- nothing so far
	}

  /*

  SITES

  */
	function sites($op = "", $op2 = "")
	{
		$this->Site =& new Site;

		$errorMsg = $this->Session->read("errorMsg");
		$Msg = $this->Session->read("Msg");
		$this->set("action", "list");
		/*
    show error message
    */
		if (!empty($errorMsg))
		{
      $this->set("errorMsg", "$errorMsg");
      $this->Session->delete("errorMsg");
    }
		/*
    show normal message
    */
		if (!empty($Msg))
		{
      $this->set("Msg", "$Msg");
      $this->Session->delete("Msg");
    }

		/*
    add site -> show adding form
    */
		if (($op == "add") || ($op == "change"))
		{
			$this->set("action", "$op");
			if ($op == "change")
			{
        $fieldsArray = $this->Site->getFieldsValue(array("s_id" => $op2), "s_name, s_url, s_user_id, s_id");
        $this->set("actionTitle", "Change site's data (<i>".$fieldsArray['Site']['s_name']."</i>)");
        $this->set("formFields", $fieldsArray['Site']);
      }
      else
      {
        $this->set("formFields", array());
        $this->set("actionTitle", "Adding new site");
      }
		}
		/*
    save site in database
    */
		elseif ($op == "save")
		{
			$this->set("action", "save");
			$siteForm = $this->data;
			$siteForm = $siteForm["Site"];
			if (empty($siteForm) || empty($siteForm['s_name']) || empty($siteForm['s_url']))
			{
        $this->Session->write("errorMsg", "Please fill all fields!");
        $this->redirect('/wf/admin/sites/add');
      }
      else
      {
        if (!empty($siteForm['s_id']))
        {
          $this->Site->setId($siteForm['s_id']);
          $this->Site->setPrimaryKey("s_id");
        }
        if ($this->Site->save($this->data))
        {
          $this->redirect('/wf/admin/sites');
        }
        else
        {
          $this->Session->write("errorMsg", "Cannot save data to database - please check fields!");
          $this->redirect('/wf/admin/sites/add');
        }
      }
		}
		/*
    default site
    */
    elseif ($op == "remove")
    {
      $err = false;
      if (is_numeric($op2))
      {
        $fieldValue = $this->Site->getFieldValue("s_name", "s_id", $op2);
        $delResult = $this->Site->query("delete from wf_sites where s_id = ".$op2);
        if (empty($delResult))
        {
          $this->Session->write("Msg", "Remove <i>$fieldValue</i> succesfully!");
          $this->redirect('/wf/admin/sites');
        }
        else
        {
          $err = true;
        }
      }
      else
      {
        $err = true;
      }

      if ($err)
      {
        $this->Session->write("errorMsg", "Cannot delete this site from database!");
        $this->redirect('/wf/admin/sites');
      }
    }
		/*
    default site
    */
		else
		{
			$rows = $this->Site->get_sites();
			$this->set("siteRows", $rows);
			$this->set("action", "list");
		}
		$this->render('admin_sites', 'admin');
	}

  /*

  BASIC TYPES

  */
	function basic_types($op = "", $op2 = "")
  {
		$this->BasicType =& new BasicType;

		$errorMsg = $this->Session->read("errorMsg");
		$Msg = $this->Session->read("Msg");
		$this->set("action", "list");
		/*
    show error message
    */
		if (!empty($errorMsg))
		{
      $this->set("errorMsg", "$errorMsg");
      $this->Session->delete("errorMsg");
    }
		/*
    show normal message
    */
		if (!empty($Msg))
		{
      $this->set("Msg", "$Msg");
      $this->Session->delete("Msg");
    }

		if (($op == "add") || ($op == "change"))
		{
			$this->set("action", "$op");
			if ($op == "change")
			{
        $fieldsArray = $this->BasicType->getFieldsValue(array("bt_id" => $op2), "bt_id, bt_name");
        $this->set("actionTitle", "Change type's data (<i>".$fieldsArray['BasicType']['bt_name']."</i>)");
        $this->set("formFields", $fieldsArray['BasicType']);
      }
      else
      {
        $this->set("formFields", array());
        $this->set("actionTitle", "Adding new basic type");
      }
		}
		/*
    save site in database
    */
		elseif ($op == "save")
		{
			$this->set("action", "save");
			$siteForm = $this->data;
			$siteForm = $siteForm["BasicType"];
			if (empty($siteForm) || empty($siteForm['bt_name']))
			{
        $this->Session->write("errorMsg", "Please fill all fields!");
        $this->redirect('/wf/admin/basic_types/add');
      }
      else
      {
        if (!empty($siteForm['bt_id']))
        {
          $this->BasicType->setId($siteForm['bt_id']);
          $this->BasicType->setPrimaryKey("bt_id");
        }
        if ($this->BasicType->save($this->data))
        {
          $this->redirect('/wf/admin/basic_types');
        }
        else
        {
          $this->Session->write("errorMsg", "Cannot save data to database - please check fields!");
          $this->redirect('/wf/admin/basic_types/add');
        }
      }
		}
		/*
    default site
    */
    elseif ($op == "remove")
    {
      $err = false;
      if (is_numeric($op2))
      {
        $fieldValue = $this->BasicType->getFieldValue("bt_name", "bt_id", $op2);
        $delResult = $this->BasicType->query("delete from wf_basic_types where bt_id = ".$op2);
        if (empty($delResult))
        {
          $this->Session->write("Msg", "Remove <i>$fieldValue</i> succesfully!");
          $this->redirect('/wf/admin/basic_types');
        }
        else
        {
          $err = true;
        }
      }
      else
      {
        $err = true;
      }

      if ($err)
      {
        $this->Session->write("errorMsg", "Cannot delete this type from database!");
        $this->redirect('/wf/admin/basic_types');
      }
    }
    /*
    default basic types
    */
    else
    {
			$rows = $this->BasicType->get_basic_types();
			$this->set("basicTypeRows", $rows);
			$this->set("action", "list");
    }
		$this->render('admin_basic_types', 'admin');
  }

  /*

  VARIABLES

  */
	function variables($op = "default", $v_param = "", $v_id = 0)
	{
		$this->Variable =& new Variable;

    /*
    *
    GROUPS
    *
    */
		if ($op == "group")
		{
  		$this->VariablesGroup =& new VariablesGroup;

  		$errorMsg = $this->Session->read("errorMsg");
  		$Msg = $this->Session->read("Msg");
  		$this->set("action", "list");
  		/*
      show error message
      */
  		if (!empty($errorMsg))
  		{
        $this->set("errorMsg", "$errorMsg");
        $this->Session->delete("errorMsg");
      }
  		/*
      show normal message
      */
  		if (!empty($Msg))
  		{
        $this->set("Msg", "$Msg");
        $this->Session->delete("Msg");
      }

  		if (($v_param == "add") || ($v_param == "change"))
  		{
  			$this->set("action", "$v_param");
  			if ($v_param == "change")
  			{
          $fieldsArray = $this->VariablesGroup->getFieldsValue(array("vt_id" => $v_id), "vt_id, vt_name");
          $this->set("actionTitle", "Change group's data (<i>".$fieldsArray['VariablesGroup']['vt_name']."</i>)");
          $this->set("formFields", $fieldsArray['VariablesGroup']);
        }
        else
        {
          $this->set("formFields", array());
          $this->set("actionTitle", "Adding new variables' group");
        }
  		}
  		/*
      save site in database
      */
  		elseif ($v_param == "save")
  		{
  			$this->set("action", "default");
  			$siteForm = $this->data;
  			$siteForm = $siteForm["VariablesGroup"];
  			if (empty($siteForm) || empty($siteForm['vt_name']))
  			{
          $this->Session->write("errorMsg", "Please fill all fields!");
          $this->redirect('/wf/admin/variables/group/add');
        }
        else
        {
          if (!empty($siteForm['vt_id']))
          {
            $this->VariablesGroup->setId($siteForm['vt_id']);
            $this->VariablesGroup->setPrimaryKey("vt_id");
          }
          //echo "<pre>".print_r($this->data, true)."</pre>";
          if ($this->VariablesGroup->save($this->data))
          {
            $this->redirect('/wf/admin/variables/group');
          }
          else
          {
            $this->Session->write("errorMsg", "Cannot save data to database - please check fields!");
            $this->redirect('/wf/admin/variables/group/add');
          }
        }
  		}
  		/*
      default site
      */
      elseif ($v_param == "remove")
      {
        $err = false;
        if (is_numeric($v_id))
        {
          $fieldValue = $this->VariablesGroup->getFieldValue("vt_name", "vt_id", $v_id);
          $delResult = $this->VariablesGroup->query("delete from wf_variable_types where vt_id = ".$v_id);
          if (empty($delResult))
          {
            $this->Session->write("Msg", "Remove <i>$fieldValue</i> succesfully!");
            $this->redirect('/wf/admin/variables/group');
          }
          else
          {
            $err = true;
          }
        }
        else
        {
          $err = true;
        }

        if ($err)
        {
          $this->Session->write("errorMsg", "Cannot delete this group!");
          $this->redirect('/wf/admin/variables/group');
        }
      }
      /*
      default variables group
      */
      else
      {
  			$rows = $this->VariablesGroup->get_variables_group();
  			$this->set("varGroupTypeRows", $rows);
  			$this->set("action", "list");
      }

			$this->render('admin_variables_group', 'admin');
		}
		elseif ($op == "sites")
		{
  		$this->VariablesLibrary =& new VariablesLibrary;
  		$this->VariablesGroup =& new VariablesGroup;
  		$this->VariablesSites =& new VariablesSites;
  		$this->Site =& new Site;
  		$this->BasicType =& new BasicType;

      // select variable type from select list
			$groupForm = $this->data;
			//echo "<pre>".print_r($groupForm, true)."</pre>";
			$groupFormId = 0;
			$vt_id = 0;
			if (!empty($groupForm))
      {
				if (!empty($groupForm['Site']['s_id']))
				{
					$groupFormId = $groupForm['Site']['s_id'];
				}
				else
				{
					if (!empty($groupForm['VariablesSites']['vs_s_id']))
					{
						$groupFormId = $groupForm['VariablesSites']['vs_s_id'];
					}
				}

				if (!empty($groupForm['VariablesGroup']['vt_id']))
				{
					$vt_id = $groupForm['VariablesGroup']['vt_id'];
				}
      }
      if ($v_param == "list")
      {
        $groupFormId = $v_id;
      }

      // get sites
      $groups = $this->Site->get_list_sites();
  		$this->set("selectOptions", $groups);
  		$this->set("groupFormId", $groupFormId);

			// get variables groups
			$variablesGroup = $this->VariablesGroup->getListVariablesGroup();
  		$this->set("groupOptions", $variablesGroup);
  		$this->set("vtFormId", $vt_id);

  		$errorMsg = $this->Session->read("errorMsg");
  		$Msg = $this->Session->read("Msg");
  		$this->set("action", "list");
  		/*
      show error message
      */
  		if (!empty($errorMsg))
  		{
        $this->set("errorMsg", "$errorMsg");
        $this->Session->delete("errorMsg");
      }
  		/*
      show normal message
      */
  		if (!empty($Msg))
  		{
        $this->set("Msg", "$Msg");
        $this->Session->delete("Msg");
      }

  		/*
      save site in database
      */
  		if ($v_param == "save")
  		{
  			$this->set("action", "list");
  			$siteForm = $this->data;
  			//echo "<pre>".print_r($siteForm, true)."</pre>";

        //form's data
        $submitData = $this->data;
  			$submitSites = $submitData['VariablesSites'];
 				$s_id = $submitSites['s_id'];

   			$libraryArray = $this->VariablesLibrary->get_variables_with_default($vt_id);
        $this->VariablesSites->query("begin");
        foreach ($libraryArray as $id => $libraries)
        {
  				$library = $libraries[0];
  				$vs_v_id = "vs_v_id_".$library['v_id'];
  				$vs_is_default = "vs_default_id_".$library['v_id'];
  				$vID = $default = 0;
          if ($submitSites[$vs_v_id] == $library['v_id'])
          {
            $vID = $library['v_id'];
          }
          if ($submitSites[$vs_is_default] == $library['v_id'])
          {
            $default = 1;
          }

          if ($vID>0)
          {
            $varSites = array('vs_v_id' => $vID, 'vs_s_id' => $s_id, 'vs_use_default' => $default);

            $delResult = $this->VariablesSites->query("delete from wf_variables_sites where vs_s_id = ".$s_id." and vs_v_id = ".$vID);
            if (empty($delResult))
            {
              $this->VariablesSites->create();
              $this->VariablesSites->save($varSites);
            }
            else
            {
              $this->VariablesSites->query("rollback");
              $this->Session->write("errorMsg", "Cannot save data to database - please check fields!");
              $this->redirect("/wf/admin/variables/sites/list/$s_id");
            }
          }
          else
          {
            $vID = $library['v_id'];
            $delResult = $this->VariablesSites->query("delete from wf_variables_sites where vs_s_id = ".$s_id." and vs_v_id = ".$vID);
            if (!empty($delResult))
            {
              $this->VariablesSites->query("rollback");
              $this->Session->write("errorMsg", "Cannot save data to database - please check fields!");
              $this->redirect("/wf/admin/variables/sites/list/$s_id");
            }
          }
        }
        $this->VariablesSites->query("commit");
        $this->redirect("/wf/admin/variables/sites/list/$s_id");
  		}
  		/*
      default site
      */
      elseif ($v_param == "remove")
      {
        $this->redirect("/wf/admin/variables/sites/list");
      }
      /*
      default variables sites
      */
      else
      {
  			$rows = array();
  			if ($groupFormId > 0)
  			{
    			$libraryArray = $this->VariablesLibrary->get_variables_with_default($vt_id);
    			$variablesSiteArray = $this->VariablesSites->get_variables_site($groupFormId);
    			$variablesSiteArray = $this->VariablesSites->serialize($variablesSiteArray, "vs_v_id");
    			$basicTypes = $this->BasicType->getListBasicTypes();

    			foreach ($libraryArray as $id => $libraries)
    			{
  					$library = $libraries[0];
  					$temp = array();
  					$temp[$library['v_id']] = $library;
  					$temp[$library['v_id']]["vt_name"] = $variablesGroup[$library['v_vt_id']];
  					if (!empty($variablesSiteArray[$library['v_id']]))
  					{
              $rows[$library['v_id']] = array_merge($temp[$library['v_id']], $variablesSiteArray[$library['v_id']]);
            }
            else
            {
              $rows[$library['v_id']] = $temp[$library['v_id']];
            }
          }
  				//echo "<pre>".print_r($variablesSiteArray, true)."</pre>";
  			}

  			$this->set("varTypeRows", $rows);
  			$this->set("action", "list");
      }

			$this->render('admin_variables_sites', 'admin');
		}
		elseif ($op == "values")
		{
  		$this->VariablesLibrary =& new VariablesLibrary;
  		$this->VariablesBasicType =& new VariablesBasicType;
  		$this->VariablesSites =& new VariablesSites;
  		$this->Site =& new Site;
  		$this->BasicType =& new BasicType;
  		$this->VariablesSiteValues =& new VariablesSiteValues;

      $siteID = (!empty($v_param))?$v_param:""; //site
      $variableID = $v_id; // variable id

      if ($v_param != "save")
      {
        // select variable type from select list
        if (empty($siteID) || empty($variableID))
        {
          $this->Session->write("errorMsg", "Incorect identifier of site or variable!");
          $this->redirect("/wf/admin/variables/sites/list/$siteID");
        }
      }

      // get sites
  		$errorMsg = $this->Session->read("errorMsg");
  		$Msg = $this->Session->read("Msg");
  		$this->set("action", "list");
  		/*
      show error message
      */
  		if (!empty($errorMsg))
  		{
        $this->set("errorMsg", "$errorMsg");
        $this->Session->delete("errorMsg");
      }
  		/*
      show normal message
      */
  		if (!empty($Msg))
  		{
        $this->set("Msg", "$Msg");
        $this->Session->delete("Msg");
      }

  		/*
      save site in database
      */
  		if (($v_param == "save") || ($v_param == "change"))
  		{
        $param = $this->data;
        $basicType = $param['BasicType']['basicType'];
        $param = $param['VariablesSiteValues'];
        $saveData = array();
        $isSave = false;
        $s_id = $param['vv_s_id'];
        switch ($basicType)
        {
          case "string":
          case "integer":
          case "long":
          case "boolean":
          case "text":
          case "float":
					{
						$delResult = $this->VariablesSiteValues->query("delete from wf_variables_sites_values where vv_s_id = ".$param['vv_s_id']." and vv_v_id = ".$param['vv_v_id']);
        		if (empty($delResult))
						{
							$isSave = $this->VariablesSiteValues->save($param);
						}
						break;
					}
          case "array":
          {
						$delResult = $this->VariablesSiteValues->query("delete from wf_variables_sites_values where vv_s_id = ".$param['vv_s_id']." and vv_v_id = ".$param['vv_v_id']);
        		if (empty($delResult))
						{
							foreach ($param['vv_value'] as $id => $values)
							{
								$saveData = array();
								$saveData = array('vv_s_id' => $param['vv_s_id'], 'vv_v_id' => $param['vv_v_id']);
								$saveData['vv_value_key'] = $id;
								$saveData['vv_value'] = $values;
								$this->VariablesSiteValues->create();
								$isSave = $this->VariablesSiteValues->save($saveData);
							}
						}
						break;
          }
          case "hash table":
          {
						$delResult = $this->VariablesSiteValues->query("delete from wf_variables_sites_values where vv_s_id = ".$param['vv_s_id']." and vv_v_id = ".$param['vv_v_id']);
        		if (empty($delResult))
						{
							foreach ($param['vv_value'] as $id => $values)
							{
								$valueArray = explode("=>", $values);
								if (count($valueArray) == 2)
								{
									$saveData = array('vv_s_id' => $param['vv_s_id'], 'vv_v_id' => $param['vv_v_id']);
									$saveData['vv_value_key'] = $valueArray[0];
									$saveData['vv_value'] = $valueArray[1];
									$this->VariablesSiteValues->create();
									$isSave = $this->VariablesSiteValues->save($saveData);
								}
							}
						}
						break;
          }
			 		default:
					{
						$isSave = false;
						break;
					}
        }
        if ($isSave)
        {
					$this->Session->write("Msg", "Save data to database - successfully!");
		   	}
		   	else
		   	{
					$this->Session->write("errorMsg", "Save data to database failed!");
        }
				$this->redirect("/wf/admin/variables/sites/list/$s_id");
  		}
      /*
      default variables sites
      */
      else
      {
        $variableType = $this->VariablesBasicType->get_variables_types_not_default($variableID);
        $basicTypes = $this->BasicType->getListBasicTypes();
        $sitesList = $this->Site->get_list_sites();
        //$variableSiteVal = $this->VariablesSiteValues->get_variables_site_values($siteID, $variableID);
        $variableSiteVal = $this->VariablesSiteValues->getListVariableValues($siteID, $variableID);

        if (in_array($basicTypes[$variableType['vbt_bt_id']], array("array", "hash table")))
        {
					$variableValues = array();
					if (!empty($variableSiteVal))
					{
						foreach ($variableSiteVal as $vv_value_key => $vv_value)
						{
							if (is_numeric($vv_value_key))
							{
								$variableValues[$vv_value] = $vv_value;
							}
							else
							{
								$variableValues[$vv_value_key."=>".$vv_value] = $vv_value_key."=>".$vv_value;
							}
						}
					}
				}
				else // string, float ... etc
				{
					$variableValues = "";
					if (!empty($variableSiteVal))
					{
						list(,$variableValues) = each($variableSiteVal);
					}
				}

        $valuesArray = array("typeBasicID" => $variableType['vbt_bt_id'], "typeBasicName" => $basicTypes[$variableType['vbt_bt_id']]);
        $valuesArray['variableID'] = $variableType['v_id'];
        $valuesArray['variableName'] = $variableType['v_name'];
        $valuesArray['variableDesc'] = $variableType['v_desc'];

        $this->set("siteInfo", array("siteID" => $siteID, "siteName" => $sitesList[$siteID]));
        $this->set("valuesInfo", $valuesArray);
        $this->set("variableValues", $variableValues);
  			$this->set("action", "list");
      }

			$this->render('admin_variables_values', 'admin');
		}
		/*
		*
		* LIBRARY WITH VARIABLES
		*
		*/
		elseif ($op == "library")
		{
  		$this->VariablesLibrary =& new VariablesLibrary;
  		$this->VariablesGroup =& new VariablesGroup;
  		$this->BasicType =& new BasicType;
  		$this->VariablesBasicType = & new VariablesBasicType;

      // select variable type from select list
			$groupForm = $this->data;
			$groupFormId = 0;
			if (!empty($groupForm))
      {
        $groupFormId = (empty($groupForm['VariablesLibrary']['vt_id']))?$groupForm['VariablesLibrary']['v_vt_id']:$groupForm['VariablesLibrary']['vt_id'];
      }
      if (($v_param == "list") || ($v_param == "add"))
      {
        $groupFormId = $v_id;
      }
      $groups = $this->VariablesGroup->getListVariablesGroup();

  		$this->set("selectOptions", $groups);
  		$this->set("groupFormId", $groupFormId);

  		$errorMsg = $this->Session->read("errorMsg");
  		$Msg = $this->Session->read("Msg");
  		$this->set("action", "list");
  		/*
      show error message
      */
  		if (!empty($errorMsg))
  		{
        $this->set("errorMsg", "$errorMsg");
        $this->Session->delete("errorMsg");
      }
  		/*
      show normal message
      */
  		if (!empty($Msg))
  		{
        $this->set("Msg", "$Msg");
        $this->Session->delete("Msg");
      }

      if (($v_param == "add") || ($v_param == "change"))
  		{
        $basicTypes = $this->BasicType->getListBasicTypes();
  		  $this->set("basicTypeOptions", $basicTypes);

    		$this->set("v_bt_selected", 1);
    		$this->set("v_bt_id", $groupFormId);

  			$this->set("action", "$v_param");
  			if ($v_param == "change")
  			{
          // information about variables
          $fieldsArray = $this->VariablesLibrary->getFieldsValue(array("v_id" => $v_id), "v_id, v_name, v_desc, v_vt_id, v_user_id");

          // variables <=> basic types
          $_tmpArray = $this->VariablesBasicType->get_variables_group("vbt_v_id = $v_id");
          $fieldsVarBasicTypeArray = array();
          foreach ($_tmpArray as $id => $VBTArray)
          {
            $vbt_bt_id = $VBTArray['VariablesBasicType']['vbt_bt_id'];
            $fieldsVarBasicTypeArray[$vbt_bt_id] = $VBTArray['VariablesBasicType'];
          }

          $this->set("actionTitle", "Change informations for <i>".$fieldsArray['VariablesLibrary']['v_name']."</i> variable");
          $this->set("formFields", $fieldsArray['VariablesLibrary']);
          $this->set("formVarBasicTypeFields", $fieldsVarBasicTypeArray);
        }
        else
        {
          $this->set("formFields", array());
          $this->set("actionTitle", "Adding new variable");
        }
  		}
  		/*
      save site in database
      */
  		elseif ($v_param == "save")
  		{
  			$this->set("action", "default");
  			$siteForm = $this->data;
  			$siteForm = $siteForm["VariablesLibrary"];
  			if (empty($siteForm) || empty($siteForm['v_name']) || empty($siteForm['v_vt_id']))
  			{
          $this->Session->write("errorMsg", "Please fill all fields!");
          $this->redirect('/wf/admin/variables/library/add');
        }
        else
        {
          if (!empty($siteForm['v_id']))
          {
            $this->VariablesLibrary->setId($siteForm['v_id']);
            $this->VariablesLibrary->setPrimaryKey("v_id");
          }
          $varLibrary = $this->data['VariablesLibrary'];
          $v_vt_id = $varLibrary["v_vt_id"];
          if ($this->VariablesLibrary->save($varLibrary))
          {
            /* save library basic types */
            if (!empty($siteForm['v_id'])) // change
            {
              $v_id = $siteForm['v_id'];
              $delResult = $this->VariablesBasicType->query("delete from wf_variables_basic_types where vbt_v_id = ".$v_id);
            }
            else // new
            {
              $v_id = $this->VariablesLibrary->getLastInsertID();
            }
            $basicTypes = $this->BasicType->getListBasicTypes();
            $varBasicType = $this->data['VariablesBasicType'];
            //echo "<pre>".print_r($varBasicType, true)."</pre>";
            unset($this->data);
            foreach ($basicTypes as $id => $BasicType)
            {
              $field = "vbt_bt_id_$id";
              $fValue = "vbt_value_$id";
              $is_default = (!empty($varBasicType['vbt_is_default']))? $varBasicType['vbt_is_default'] : 0;
              if (($varBasicType[$field] == $id) || ($is_default == $id))
              {
                $vbt_is_default = ($is_default == $id)?1:0;
                $vbt_value = ($varBasicType[$fValue])?$varBasicType[$fValue]:"";
                $this->data['VariablesBasicType']['vbt_v_id'] = $v_id;
                $this->data['VariablesBasicType']['vbt_bt_id'] = $id;
                $this->data['VariablesBasicType']['vbt_is_default'] = $vbt_is_default;
                $this->data['VariablesBasicType']['vbt_value'] = $vbt_value;
                $this->VariablesBasicType->create();
                $this->VariablesBasicType->save($this->data);
                //echo "<pre>".print_r($this->data, true)."</pre>";
              }
            }
            $this->redirect("/wf/admin/variables/library/list/$v_vt_id");
          }
          else
          {
            $this->Session->write("errorMsg", "Cannot save data to database - please check fields!");
            $this->redirect('/wf/admin/variables/library/add');
          }
        }
  		}
  		/*
      default site
      */
      elseif ($v_param == "remove")
      {
        $err = false;
        if (is_numeric($v_id))
        {
          $fieldValue = $this->VariablesLibrary->getFieldsValue(array("v_id" => $v_id), "v_name, v_vt_id");
          $v_vt_id = $fieldValue['VariablesLibrary']['v_vt_id'];
          $delResult = $this->VariablesLibrary->query("delete from wf_variables where v_id = ".$v_id);
          if (empty($delResult))
          {
            $delResult = $this->VariablesBasicType->query("delete from wf_variables_basic_types where vbt_v_id = ".$v_id);
            if (empty($delResult))
            {
              $this->Session->write("Msg", "Remove <i>".$fieldValue['VariablesLibrary']['v_name']."</i> succesfully!");
              $this->redirect("/wf/admin/variables/library/list/$v_vt_id");
            }
          }
          else
          {
            $err = true;
          }
        }
        else
        {
          $err = true;
        }

        if ($err)
        {
          $this->Session->write("errorMsg", "Cannot delete this group!");
          $this->redirect('/wf/admin/variables/library');
        }
      }
      /*
      default variables library
      */
      else
      {
  			$rows = $this->VariablesLibrary->get_variables($groupFormId);
  			$this->set("varTypeRows", $rows);
  			$this->set("action", "list");
      }

			$this->render('admin_variables', 'admin');
		}
		elseif ($op == "conf_header")
		{
  		$this->Site =& new Site;
  		$this->ConfigHeaderSites =& new ConfigHeaderSites;

      // select variable type from select list
			$groupForm = $this->data;
			//echo "<pre>".print_r($groupForm, true)."</pre>";
			$groupFormId = 0;
			$vt_id = 0;
			if (!empty($groupForm))
      {
				if (!empty($groupForm['Site']['s_id']))
				{
					$groupFormId = $groupForm['Site']['s_id'];
				}
      }
      if ($v_param == "list")
      {
        $groupFormId = $v_id;
      }

      // get sites
      $groups = $this->Site->get_list_sites();
  		$this->set("selectOptions", $groups);
  		$this->set("groupFormId", $groupFormId);

			// get variables groups
  		$this->set("vtFormId", $vt_id);

  		$errorMsg = $this->Session->read("errorMsg");
  		$Msg = $this->Session->read("Msg");
  		$this->set("action", "list");
  		/*
      show error message
      */
  		if (!empty($errorMsg))
  		{
        $this->set("errorMsg", "$errorMsg");
        $this->Session->delete("errorMsg");
      }
  		/*
      show normal message
      */
  		if (!empty($Msg))
  		{
        $this->set("Msg", "$Msg");
        $this->Session->delete("Msg");
      }

  		/*
      save site in database
      */
  		if ($v_param == "save")
  		{
        $param = $this->data;
        $siteID = $param['Site']['s_id'];

        if (!empty($siteID))
        {
          $saveData = array('chs_s_id' => $siteID);
          if (!empty($param['ConfigHeaderSites']['chs_id']))
          {
            $saveData['chs_id'] = $param['ConfigHeaderSites']['chs_id'];
          }
          $saveData['chs_header'] = $param['ConfigHeaderSites']['chs_header'];
          $saveData['chs_footer'] = $param['ConfigHeaderSites']['chs_footer'];
          $saveData['chs_user_id'] = 1;
          $this->ConfigHeaderSites->save($saveData);
        }

        $this->redirect('/wf/admin/variables/conf_header/list/'.$siteID);
  		}
      /*
      remove headers
      */
      elseif ($v_param == "remove")
      {
        $err = false;
        $param = $this->data;
        $siteID = $param['Site']['s_id'];
        if (is_numeric($siteID))
        {
          $siteName = $this->Site->getFieldValue("s_name", "s_id", $siteID);
          $delResult = $this->ConfigHeaderSites->query("delete from wf_config_header_sites where chs_s_id = ".$siteID);
          if (empty($delResult))
          {
            $this->Session->write("Msg", "Remove headers config for <i>$siteName</i> succesfully!");
            $this->redirect('/wf/admin/variables/conf_header/list/'.$siteID);
          }
          else
          {
            $err = true;
          }
        }
        else
        {
          $err = true;
        }

        if ($err)
        {
          $this->Session->write("errorMsg", "Cannot delete parameters!");
          $this->redirect('/wf/admin/variables/conf_header');
        }
      }
      /*
      default
      */
      else
      {
        $rows = array();
        if (!empty($groupFormId))
        {
          $rows = $this->ConfigHeaderSites->getFieldsValue(array("chs_s_id" => $groupFormId), "*");
          $rows = $rows[0];
        }
  			$this->set("configFields", $rows);
  			$this->set("action", "list");
      }

			$this->render('admin_header_footer', 'admin');
		}
		elseif ($op == "conf_includes")
		{
  		$this->Site =& new Site;
  		$this->VariablesLibrary =& new VariablesLibrary;
  		$this->ConfigIncludesSites =& new ConfigIncludesSites;

      $variables = $this->VariablesLibrary->getListVariables();
      $inclReqList = $this->ConfigIncludesSites->getIncReqList();
      $inclPlaceList = $this->ConfigIncludesSites->getInsertPlace();
      $this->set("variables", $variables);
      $this->set("includeRequestList", $inclReqList);
      $this->set("includePlaceList", $inclPlaceList);

      // select variable type from select list
			$groupForm = $this->data;
			//echo "<pre>".print_r($groupForm, true)."</pre>";
			$groupFormId = 0;
			$vt_id = 0;
			if (!empty($groupForm))
      {
				if (!empty($groupForm['Site']['s_id']))
				{
					$groupFormId = $groupForm['Site']['s_id'];
				}
				else
				{
					if (!empty($groupForm['ConfigIncludesSites']['cis_s_id']))
					{
						$groupFormId = $groupForm['ConfigIncludesSites']['cis_s_id'];
					}
				}
      }
      if (($v_param == "add") || ($v_param == "list"))
      {
        $groupFormId = $v_id;
      }

      // get sites
      $groups = $this->Site->get_list_sites();
  		$this->set("selectOptions", $groups);
  		$this->set("groupFormId", $groupFormId);

			// get variables groups
  		$this->set("vtFormId", $vt_id);

  		$errorMsg = $this->Session->read("errorMsg");
  		$Msg = $this->Session->read("Msg");
  		$this->set("action", "list");
  		/*
      show error message
      */
  		if (!empty($errorMsg))
  		{
        $this->set("errorMsg", "$errorMsg");
        $this->Session->delete("errorMsg");
      }
  		/*
      show normal message
      */
  		if (!empty($Msg))
  		{
        $this->set("Msg", "$Msg");
        $this->Session->delete("Msg");
      }

  		if (($v_param == "add") || ($v_param == "change"))
  		{
  			if ($v_param == "change")
  			{
          $cisID = $v_id;
          $fieldsArray = $this->ConfigIncludesSites->getFieldsValue(array("cis_id" => $cisID), "*");
          $this->set("formFields", $fieldsArray[0]);
        }
  			$this->set("action", $v_param);
  		}
  		/*
      save site in database
      */
  		elseif ($v_param == "save")
  		{
        $param = $this->data;
        $siteID = $param['ConfigIncludesSites']['cis_s_id'];

        if (!empty($siteID))
        {
          $this->ConfigIncludesSites->save($param);
        }
        $this->redirect('/wf/admin/variables/conf_includes/list/'.$siteID);
  		}
      /*
      remove includes
      */
      elseif ($v_param == "remove")
      {
        $err = false;
        $cisID = $v_id;
        if (is_numeric($cisID))
        {
          $siteID = $this->ConfigIncludesSites->getFieldValue("cis_s_id", "cis_id", $cisID);
          $delResult = $this->ConfigIncludesSites->query("delete from wf_config_includes_sites where cis_id = ".$cisID);
          if (empty($delResult))
          {
            $this->Session->write("Msg", "Remove include/require succesfully!");
            $this->redirect('/wf/admin/variables/conf_includes/list/'.$siteID);
          }
          else
          {
            $err = true;
          }
        }
        else
        {
          $err = true;
        }

        if ($err)
        {
          $this->Session->write("errorMsg", "Cannot delete include/require!");
          $this->redirect('/wf/admin/variables/conf_includes');
        }
      }
      /*
      */
      else
      {
  			$rows = array();
        if (!empty($groupFormId))
        {
          $rows = $this->ConfigIncludesSites->getFieldsValue(array("cis_s_id" => $groupFormId), "*");
        }
  			$this->set("configFields", $rows);
  			$this->set("action", "list");
      }

			$this->render('admin_config_includes', 'admin');
		}
		else
		{
      $this->render('admin', 'admin');
    }
	}

}

?>
